package com.laycoding.layrpc.common;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class LayRpcRegistyCache {

    public static ConcurrentHashMap<String, Object> serviceMap = new ConcurrentHashMap<>();

    private static AtomicInteger number = new AtomicInteger(1);

    public static String getLoadBlance(String name) {
        ConcurrentHashMap.KeySetView<String, Object> strings = serviceMap.keySet();
        List<String> list = new ArrayList<>();
        for (String string : strings) {
            if (serviceMap.get(string).equals(name)) {
                list.add(string);
            }
        }
        if (list.size() > 1) {
            int andIncrement = number.getAndIncrement();
            return list.get(andIncrement % list.size());
        } else if (list.size() == 1) {
            return list.get(0);
        }
        return null;
    }

    public static void removeService(String url) {
        if (serviceMap.containsKey(url)) {
            serviceMap.remove(url);
        }
    }

}
